let list=document.querySelector('.list');
for(let i=0; i<10; i++) {
	let list_item=document.createElement('div');
	let img=document.createElement('img');
	list_item.className='list_item';
	img.src='assets/imgs/loading.gif';
	img.setAttribute('data-original', 'assets/imgs/1.png');
	list_item.setAttribute('data-index',Math.floor(i/2));
	list_item.appendChild(img);
	list.appendChild(list_item);
};

let height = document.documentElement.clientHeight;

loadImg(0);

function loadImg(index) {
	let list_items=document.querySelectorAll('.list_item');
	Array.from(list_items).forEach((item, i)=>{
		if(item.dataset['index']==index) {
			item.children[0].src=item.children[0].dataset['original'];
		}
	});
}

let pages=[];
pages.push(0);


window.onscroll=debounce(function() {
	console.log('scroll');
	let scroll=this.scrollY;
	let page=Math.round(scroll/height);
	let bool=pages.some((item, i)=>item===page);
	if(!bool) {
		loadImg(page);
		pages.push(page);
	}
});

// 没有清空 timer, 在单位时间内执行一次
function debounce(fn, delay=100) {
	let timer=null;
	// timer 是闭包数据
	return function() {
		if(timer) {
			return ;
		}
		timer=setTimeout(function() {
			fn.apply(this, arguments);
			timer=null;
		}, delay);
	}
}

